package com.lancoo.androidmultichatroom.demo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.lancoo.tyjx.multichatroom.activity.CropImageActivity;
import com.lancoo.tyjx.multichatroom.activity.MyApplication;
import com.lancoo.tyjx.multichatroom.activity.PicSrcPickerActivity;
import com.lancoo.tyjx.multichatroom.adapter.ChatAdapter;
import com.lancoo.tyjx.multichatroom.constants.Constants;
import com.lancoo.tyjx.multichatroom.db.MsgDbHelper;
import com.lancoo.tyjx.multichatroom.expression.ExpressionListener;
import com.lancoo.tyjx.multichatroom.expression.ExpressionView;
import com.lancoo.tyjx.multichatroom.model.ChatItem;
import com.lancoo.tyjx.multichatroom.utils.DateUtil;
import com.lancoo.tyjx.multichatroom.utils.FileUtil;
import com.lancoo.tyjx.multichatroom.utils.ImageUtil;
import com.lancoo.tyjx.multichatroom.utils.JsonUtil;
import com.lancoo.tyjx.multichatroom.utils.SoftKeyBoardListener;
import com.lancoo.tyjx.multichatroom.utils.Tool;
import com.lancoo.tyjx.multichatroom.view.MarqueeTextView;
import com.lancoo.tyjx.multichatroom.view.MyListView;
import com.lancoo.tyjx.multichatroom.view.RecordButton;
import com.lancoo.tyjx.multichatroom.xmpp.XmppMsgType;
import com.lancoo.tyjx.multichatroom.xmpp.XmppTool;

import org.devio.takephoto.app.TakePhotoFragment;
import org.devio.takephoto.compress.CompressConfig;
import org.devio.takephoto.model.TImage;
import org.devio.takephoto.model.TResult;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import fr.castorflex.android.circularprogressbar.CircularProgressBar;

public class ChatFragment extends TakePhotoFragment implements View.OnClickListener {
    @BindView(R.id.leftBtn)
    ImageView mLeftBtn;
    @BindView(R.id.iv_upvoteoption)
    ImageView mIvUpvoteoption;
    @BindView(R.id.titleView)
    MarqueeTextView mTitleView;
    @BindView(R.id.rightBtn)
    ImageView mRightBtn;
    @BindView(R.id.titlebar)
    FrameLayout mTitlebar;
    @BindView(R.id.listView)
    MyListView mListView;

    ImageView mExpBtn;
    EditText mMsgText;
    RecordButton mRecordBtn;
    ImageView mVoice;
    RelativeLayout mEdictingLayout;
    ImageView mIvImage;
    ExpressionView mExpView;
    TextView mTvSend;
    Unbinder unbinder;
    @BindView(R.id.tv_no_resource)
    TextView mTvNoResource;
    @BindView(R.id.circle_progress)
    CircularProgressBar mCircleProgress;
    @BindView(R.id.tv_progress)
    TextView mTvProgress;
    private String chatName; // 群的时候是群名称
    private int chatType = 0;
    private List<ChatItem> chatItems = new ArrayList<>();
    private ChatAdapter adapter;
    private UpMessageReceiver mUpMessageReceiver;
    private boolean isupvote;
    private String topickName;
    private String chatRoomID;
    private String liveId;
    private static final String TAG = "RoomChatActivity";
    private String mUploadPath;
    private String mhttpAddress;
    //    private FTPUtils ftpUploadTool;
    private String mCourseID;
    private String mnamedTime;

    public static Fragment getInstance() {
        return new ChatFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_chat, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 设置自己的头像
        JsonUtil.HEADER_IMG = ConstDefine.PhotoPath;
        if (null != mExpBtn) {
            init();
        }
    }

    private void init() {
        System.out.println("RoomChatActivity.onCreate()===========" + chatType);

        initView();
        if (!TextUtils.isEmpty(chatName)) {
            initData();
        }
        mTitleView.setText(topickName);

        getFtpInfo();
        getHttpServerInfo();

        mIvImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                final Uri imageUri = Uri.fromFile(file);
                BottomPhotoDialog bottomPhotoDialog = new BottomPhotoDialog(new BottomPhotoDialog.OnClickItemListener() {
                    @Override
                    public void onClickTakePhoto() {
                        if (!XmppTool.getInstance().isconnected()) {
                            ToastUtils.showShort("与聊天室失去连接");
                            return;
                        }

                        CompressConfig config = new CompressConfig.Builder()
                                .setMaxSize(200 * 1024)
                                .setMaxPixel(1200)
                                .create();
                        getTakePhoto().onEnableCompress(config, true);
                        getTakePhoto().onPickFromCapture(imageUri);
                    }

                    @Override
                    public void onClickSelectPhoto() {
                        if (!XmppTool.getInstance().isconnected()) {
                            ToastUtils.showShort("与聊天室失去连接");
                            return;
                        }

                        CompressConfig config = new CompressConfig.Builder()
                                .setMaxSize(200 * 1024)
                                .setMaxPixel(1200)
                                .create();
                        getTakePhoto().onEnableCompress(config, true);
                        getTakePhoto().onPickFromGallery();
                    }
                });
                bottomPhotoDialog.show(getFragmentManager(), "photo");
            }
        });
        mTvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 获取text文本
                String msg = mMsgText.getText().toString();
                // 文本不为空，直接发文本消息
                if (!msg.isEmpty()) {

                    try {
                        if (!XmppTool.getInstance().isconnected()) {
                            ToastUtils.showShort("与聊天室失去连接");
                            return;
                        }

                        sendBoardToRoom(msg, 0);
                        XmppTool.getInstance().sendMsg(msg, chatType);

                        // 发送文本后关闭键盘
                        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(mMsgText.getWindowToken(), 0);

                        mExpView.setVisibility(View.GONE);
                    } catch (Exception e) {
                        autoSendIfFail(msg);
                        e.printStackTrace();
                    }
                    mMsgText.setText("");
                }
            }
        });
    }


    private void getHttpServerInfo() {
        mhttpAddress = ConstDefine.HTTP_ADDRESS;
    }

    private void getFtpInfo() {
        mUploadPath = "lgftp/OnlineClass/chat";
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        TImage image = result.getImage();
        uploadPhoto(image);
    }

    private void uploadPhoto(final TImage image) {
        final String url = mhttpAddress.replace("lgftp/", "") + mUploadPath + "/" + ToolUtil.getFileName(image.getCompressPath());

        try {
            XmppTool.getInstance().sendImage(url, image.getCompressPath(), chatType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 刷新页面 聊天
    private void initData() {
        chatItems = MsgDbHelper.getInstance(getContext())
                .getChatMsg(chatName);

        if (null == chatItems || chatItems.isEmpty()) {
            mTvNoResource.setVisibility(View.VISIBLE);
        } else {
            mTvNoResource.setVisibility(View.INVISIBLE);
        }

        adapter.initDataSource(chatItems);
        adapter.notifyDataSetChanged();
        mListView.setSelection(adapter.getCount() + 1);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                mListView.onRefreshComplete();
                List<ChatItem> moreChatItems = MsgDbHelper.getInstance(
                        getContext()).getChatMsgMore(
                        mListView.getCount() - 1, chatName);
                for (int i = 0; i < moreChatItems.size(); i++) {
                    chatItems.add(i, moreChatItems.get(i));
                }
                adapter.initDataSource(chatItems);
                adapter.notifyDataSetChanged();
            }
        }
    };

    private void initView() {
        mLeftBtn.setOnClickListener(this);
        mRightBtn.setOnClickListener(this);
        mVoice.setOnClickListener(this);
        mExpBtn.setOnClickListener(this);
        mIvUpvoteoption.setOnClickListener(this);

        mRecordBtn.setActivity((AppCompatActivity) getActivity());

        adapter = new ChatAdapter(getContext(), chatName, getFragmentManager(), new ChatAdapter.OnAudioPlayListener() {
            @Override
            public void prepare() {
                if (null != getActivity()) {
                }
            }

            @Override
            public void complete() {
            }
        },
                new ChatAdapter.OnFileClickListener() {
                    @Override
                    public void onCLick(String fileUrl) {
                        String url = ToolUtil.decodeJson(fileUrl);

//                        int mcurFileType = FileType.getFileType(url);
//                        String fileName = ToolUtil.getFileName(url);
//
//                        if (mcurFileType == FileType.VIDEO) {
//                            Intent intent = new Intent(getContext(), TyjxPreviewVideoActivity.class);
//                            intent.putExtra("data", url);
//                            intent.putExtra("title", fileName);
//                            getContext().startActivity(intent);
//                        } else if (mcurFileType == FileType.AUDIO) {
//                            Intent intent = new Intent(getContext(), TyjxPreviewMusicActivity.class);
//                            intent.putExtra("data", url);
//                            intent.putExtra("title", fileName);
//                            getContext().startActivity(intent);
//                        } else if (mcurFileType == FileType.IMAGE) {
//                            Intent intent = new Intent(getContext(), TyjxPreviewPhotoActivity.class);
//                            intent.putExtra("data", url);
//                            intent.putExtra("title", fileName);
//                            getContext().startActivity(intent);
//                        } else {
//                            if (ToolUtil.isAppInstalled(getContext(), "cn.wps.moffice_eng")) {
//                                ToolUtil.openfile(ToolUtil.decodeJson(url), getContext());
//                            } else {
//                                Toast.makeText(getContext(), "请安装WPS后进行预览", Toast.LENGTH_SHORT).show();
//                            }
//                        }
                    }
                });
        adapter.initDataSource(chatItems);
        mListView.setAdapter(adapter);
        mListView.setonRefreshListener(new MyListView.OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(0);
                    }
                }).start();
            }
        });

        mMsgText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (null != mExpBtn) {
                    mExpView.setVisibility(View.GONE);
                }
            }
        });
        mMsgText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
//                if ("".equals(mMsgText.getText().toString())) {
//                    mIvImage.setImageResource(R.drawable.icon_chat_image);
//                } else {
//                    mIvImage.setImageResource(R.drawable.icon_send_w);
//                }
            }
        });

        mRecordBtn.setOnFinishedRecordListener(new RecordButton.OnFinishedRecordListener() {
            @Override
            public void onStartRecord() {
                adapter.stopPlayer();

            }

            @Override
            public void onFinishedRecord(String audioPath, int time) {

                if (!XmppTool.getInstance().isconnected()) {
                    ToastUtils.showShort("与聊天室失去连接");
                    return;
                }

                if (audioPath != null) {
                    try {
                        sendBoardToRoom(Constants.SAVE_SOUND_PATH + "/" + FileUtil.getFileName(audioPath), 0);
                        XmppTool.getInstance().sendMsgWithParms(
                                FileUtil.getFileName(audioPath),
                                new String[]{"imgData", "Duration"},
                                new Object[]{ImageUtil
                                        .getBase64StringFromFile(audioPath), time},
                                chatType, XmppMsgType.AUDIO);
                    } catch (Exception e) {
                        autoSendIfFail(FileUtil.getFileName(audioPath),
                                new String[]{"imgData"},
                                new Object[]{ImageUtil
                                        .getBase64StringFromFile(audioPath)}, XmppMsgType.AUDIO);
                        e.printStackTrace();
                    }
                } else {
                    Tool.initToast(getActivity(), "发送失败");
                }

            }
        });
        mExpView.setEditText(mMsgText);
        mExpView.setGifListener(new ExpressionListener() {
            @Override
            public void clickGif(String msg) {
                try {
                    XmppTool.getInstance().sendMsg(msg, chatType);
                    sendBoardToRoom(msg, 0);
                } catch (Exception e) {
                    autoSendIfFail(msg);
                    e.printStackTrace();
                }
            }
        });

        SoftKeyBoardListener.setListener(getActivity(), new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                if (null == mExpView) {
                    return;
                }
                mExpView.setVisibility(View.GONE);
                // Determine the voice
                if (mMsgText.getVisibility() == View.GONE) {
                    mMsgText.setVisibility(View.VISIBLE);
                    mRecordBtn.setVisibility(View.GONE);
//                    if ("".equals(mMsgText.getText().toString())) {
//                        CURRENT_MODE = MODE_PICTURE;
//                        mIvImage.setImageResource(R.drawable.icon_chat_image);
//                    } else {
//                        CURRENT_MODE = MODE_SEND;
//                        mIvImage.setImageResource(R.drawable.icon_send_w);
//                    }
                }
            }

            @Override
            public void keyBoardHide(int height) {
//                CURRENT_MODE = MODE_PICTURE;
//                mIvImage.setImageResource(R.drawable.icon_chat_image);
            }
        });

        // 会话内容改变，接受广播
        if (mUpMessageReceiver == null) {
            mUpMessageReceiver = new UpMessageReceiver();
        }
        getActivity().registerReceiver(mUpMessageReceiver, new IntentFilter("ChatNewMsg"));
        getActivity().registerReceiver(mUpMessageReceiver, new IntentFilter("LeaveRoom"));

    }

    @Override
    public void onClick(View v) {


        if (v.getId() == R.id.rightBtn) {
            if (chatType == ChatItem.CHAT) {
                Tool.initToast(getActivity(), "FriendActivity.class");
                // intent.setClass(getApplicationContext(),
                // FriendActivity.class);
                // intent.putExtra("username", chatName);
                // startActivity(intent);
            } else if (chatType == ChatItem.GROUP_CHAT) {
                Tool.initToast(getActivity(), "RoomMemActivity.class");
                // intent.setClass(getApplicationContext(),
                // RoomMemActivity.class);
                // intent.putExtra("roomName", chatName);
                // startActivity(intent);
            }
        } else if (v.getId() == R.id.sendBtn) {
            if (mRecordBtn.getVisibility() == View.GONE) { // 文本为空，从文本输入模式切换到语音输入模式
                mMsgText.setVisibility(View.GONE);
                mRecordBtn.setVisibility(View.VISIBLE);
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mMsgText.getWindowToken(), 0);
                mExpView.setVisibility(View.GONE);
                mVoice.setImageResource(R.drawable.icon_keyboard);
            } else if (mMsgText.getVisibility() == View.GONE) { // 文本为空，从语音输入模式切换到文本输入模式
                mMsgText.setVisibility(View.VISIBLE);
                mRecordBtn.setVisibility(View.GONE);
                mVoice.setImageResource(R.drawable.icon_chat_voice);
            }
        } else if (v.getId() == R.id.msgText)// 选中文本框，聊天记录弹到最后一条
        {
            mExpView.setVisibility(View.GONE);
            mListView.setSelection(adapter.getCount()); // 去到最后一行
        } else if (v.getId() == R.id.takePicBtn)// 拍照
        {
            Intent intent1 = new Intent();
            CropImageActivity.isAutoSend = true;
            intent1.setClass(getContext(), PicSrcPickerActivity.class);
            intent1.putExtra("type", PicSrcPickerActivity.TAKE_PIC);
            startActivityForResult(intent1, PicSrcPickerActivity.CROP);
        } else if (v.getId() == R.id.chosePicBtn) // 图库
        {
            Intent intent2 = new Intent();
            CropImageActivity.isAutoSend = true;
            intent2.setClass(getContext(), PicSrcPickerActivity.class);
            intent2.putExtra("type", PicSrcPickerActivity.CHOSE_PIC);
            startActivityForResult(intent2, PicSrcPickerActivity.CROP);
        } else if (v.getId() == R.id.expBtn)// 点击表情icon
        {
            if (mExpView.getVisibility() == View.GONE) {
                InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (null != getActivity().getCurrentFocus()) {
                    inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus()
                            .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
                mExpView.setVisibility(View.VISIBLE);
//                mMoreLayout.setVisibility(View.GONE);
            } else {
                mExpView.setVisibility(View.GONE);
            }
            // Determine the voice
            if (mMsgText.getVisibility() == View.GONE) {
                mMsgText.setVisibility(View.VISIBLE);
                mRecordBtn.setVisibility(View.GONE);
            }
        } else if (v.getId() == R.id.iv_upvoteoption) {
            Boolean isUpVote = Constants.voteState.get(liveId);
            if (isUpVote) {
                Constants.isupvote = false;
                mIvUpvoteoption.setBackgroundResource(R.drawable.chat_upvote_not);
                try {
                    XmppTool.getInstance().sendLikeMsg("unlike", ChatItem.GROUP_CHAT);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Constants.isupvote = true;
                mIvUpvoteoption.setBackgroundResource(R.drawable.chat_upvote_has);
                try {
                    XmppTool.getInstance().sendLikeMsg("like", ChatItem.GROUP_CHAT);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Constants.voteState.put(liveId, Constants.isupvote);
        }

    }

    private class UpMessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 收到廣播更新我们的界面
            if (intent.getAction().equals("LeaveRoom")) {
//                finish();
            } else if (intent.getAction().equals("ChatNewMsg")) {
                initData();
            }
        }
    }

    public void sendBoardToRoom(String msgBody, int sendState) {
        ChatItem chatItem = new ChatItem(chatType, chatName, chatName + "@conference." + Constants.SERVER_HOST,
                JsonUtil.HEADER_IMG, msgBody, DateUtil.now_MM_dd_HH_mm_ss(), 1, sendState);
        if (sendState == 0) {//正在发送
            chatItems.add(chatItem);
            adapter.initDataSource(chatItems);
            adapter.notifyDataSetChanged();
            mListView.setSelection(adapter.getCount() + 1);
        } else {//发送失败
            MsgDbHelper.getInstance(MyApplication.getInstance()).saveChatMsg(chatItem);
            MyApplication.getInstance().sendBroadcast(new Intent("ChatNewMsg"));
        }
    }

    public void autoSendIfFail(final String msg) {
//		Tool.initToast(MyApplication.getInstance(), "发送中..");
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() { // 1秒后开始
            int count = 0;

            @Override
            public void run() {
                try {
                    count++;
                    if (!isLeaving) {
                        XmppTool.getInstance().setRecevier(chatName,
                                chatType);
                        XmppTool.getInstance().sendMsg(msg, chatType);
                        timer.cancel();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Log.e("muc", "autosend      " + count);
                    if (count > 8) {
                        sendBoardToRoom(msg, 2);
                        Tool.initToast(MyApplication.getInstance(),
                                "发送失败");
                        timer.cancel();
                    }
                }
            }
        }, 1000, 1000);
    }

    // 下面是断线发不出内容时自动重发
    public static boolean isLeaving = false;

    public void autoSendIfFail(final String msg, final String[] s,
                               final Object[] obj, final XmppMsgType msgType) {
//		Tool.initToast(MyApplication.getInstance(), "发送中..");
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() { // 1秒后开始
            int count = 0;

            @Override
            public void run() {
                try {
                    count++;
                    if (!isLeaving) {
                        XmppTool.getInstance().setRecevier(chatName,
                                chatType);
                        XmppTool.getInstance().sendMsgWithParms(msg, s,
                                obj, chatType, msgType);
                        timer.cancel();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Log.e("muc", "autosend      " + count);
                    if (count > 8) {
                        if (msg.endsWith(".jpg")) {
                            sendBoardToRoom(Constants.SAVE_IMG_PATH + "/" + msg, 2);
                        } else if (msg.endsWith(".amr") || msg.endsWith("aec")) {
                            sendBoardToRoom(Constants.SAVE_SOUND_PATH + "/" + msg, 2);
                        }
                        Tool.initToast(MyApplication.getInstance(),
                                "发送失败");
                        timer.cancel();
                    }
                }
            }
        }, 1000, 1000);
    }

    public void setMessage(String courseId, String roomId, String topickName, String chatName, String liveId, int chatType,
                           ImageView expBtn,
                           EditText msgText,
                           RecordButton recordBtn,
                           ImageView voice,
                           RelativeLayout edictingLayout,
                           ImageView ivImage,
                           ExpressionView expView, TextView tvSend) {
        this.mCourseID = courseId;
        this.chatRoomID = roomId;
        this.topickName = topickName;
        this.chatName = chatName;
        this.liveId = liveId;
        this.chatType = chatType;

        this.mExpBtn = expBtn;
        this.mMsgText = msgText;
        this.mRecordBtn = recordBtn;
        this.mVoice = voice;
        this.mEdictingLayout = edictingLayout;
        this.mIvImage = ivImage;
        this.mExpView = expView;
        this.mTvSend = tvSend;

        if (null != mListView) {
            this.showSuccess(true);
            init();
        }
    }

    public void showSuccess(boolean isSuccess) {
        if (isSuccess) {
            mCircleProgress.setVisibility(View.INVISIBLE);
            mTvProgress.setVisibility(View.INVISIBLE);
        } else {
            mCircleProgress.setVisibility(View.GONE);
            mTvProgress.setText("加入课堂交流失败");
        }
    }

    @Override
    public void onDestroyView() {
        unbinder.unbind();
//        EventBus.getDefault().unregister(this);
        if (null != mUpMessageReceiver) {
            if (null != getActivity()) {
                getActivity().unregisterReceiver(mUpMessageReceiver);
            }
        }
        super.onDestroyView();
    }
}
